/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.util;

import com.camachosanchez.gui.Principal;
import com.toedter.calendar.JDateChooser;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.swing.*;
import javax.swing.plaf.basic.BasicToolBarUI;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
//import org.icepdf.ri.common.ComponentKeyBinding;
//import org.icepdf.ri.common.SwingController;
//import org.icepdf.ri.common.SwingViewBuilder;

/**
 *
 * @author Rolando
 */
public class GUIUtil {

    public static String getNombreEncargado() {
        String encargado = "";
        try {
            InputStream is = new FileInputStream("empresa.properties");
            Properties prop = new Properties();
            prop.load(is);
            encargado = prop.getProperty("encargado");
            is.close();
        } catch (Exception e) {
            encargado = "";
        }
        return encargado;
    }

    public static void addEscapeKey(final JDialog dialog) {
        KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
        Action escapeAction = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        };
        dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
        dialog.getRootPane().getActionMap().put("ESCAPE", escapeAction);
    }

//    public static void getCurrentUser() {
//        UsuariosJpaController user = new UsuariosJpaController(null);
//        if (!user.findUsuariosEntities().isEmpty()) {
//            currentUser = user.findUsuariosEntities().get(1);
//        } else {
//            currentUser = null;
//        }
//    }
//    public static Usuarios currentUser() {
//        UsuariosJpaController user = new UsuariosJpaController(null);
//        if (!user.findUsuariosEntities().isEmpty()) {
//            return user.findUsuariosEntities().get(0);
//        } else {
//            return null;
//        }
//    }
    public static void limpiarVentana(Component[] componentes) {
        int tam = componentes.length;
        for (int i = 0; i < tam; i++) {
            if (componentes[i] instanceof JTextField) {
                ((JTextField) componentes[i]).setText("");
            } else if (componentes[i] instanceof JComboBox) {
                if (((JComboBox) componentes[i]).getItemCount() > 0) {
                    ((JComboBox) componentes[i]).setSelectedIndex(0);
                }
            } else if (componentes[i] instanceof JDateChooser) {
                ((JDateChooser) componentes[i]).setDate(new Date());
            } else if (componentes[i] instanceof JSpinner) {
                ((JSpinner) componentes[i]).setValue(0);
            } else if (componentes[i] instanceof JTextPane) {
                ((JTextPane) componentes[i]).setText("");
            } else if (componentes[i] instanceof JCheckBox) {
                ((JCheckBox) componentes[i]).setSelected(false);
            } else if (componentes[i] instanceof JPanel) {
                limpiarVentana(((JPanel) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JLayeredPane) {
                limpiarVentana(((JLayeredPane) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JTabbedPane) {
                limpiarVentana(((JTabbedPane) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JScrollPane) {
                limpiarVentana(((JScrollPane) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JViewport) {
                limpiarVentana(((JViewport) componentes[i]).getComponents());
            }
        }

    }

    public static void deshabilitarVentana(Component[] componentes) {
        int tam = componentes.length;
        for (int i = 0; i < tam; i++) {
            if (componentes[i] instanceof JTextField || componentes[i] instanceof JComboBox
                    || componentes[i] instanceof JDateChooser || componentes[i] instanceof JSpinner
                    || componentes[i] instanceof JCheckBox || componentes[i] instanceof JTextPane
                    || componentes[i] instanceof JButton) {
                componentes[i].setEnabled(false);
            } else if (componentes[i] instanceof JPanel) {
                deshabilitarVentana(((JPanel) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JLayeredPane) {
                deshabilitarVentana(((JLayeredPane) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JTabbedPane) {
                deshabilitarVentana(((JTabbedPane) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JScrollPane) {
                deshabilitarVentana(((JScrollPane) componentes[i]).getComponents());
            } else if (componentes[i] instanceof JViewport) {
                deshabilitarVentana(((JViewport) componentes[i]).getComponents());
            }
        }

    }

    public static void SetAnchoColumnas(javax.swing.JTable tabla) {
        int nroFilas = tabla.getRowCount();
        int nroColumnas = tabla.getColumnCount();
        tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        for (int columna = 0; columna < nroColumnas; columna++) {
            TableCellRenderer renderer = tabla.getColumnModel().getColumn(columna).getHeaderRenderer();
            if (renderer == null) {
                renderer = tabla.getTableHeader().getDefaultRenderer();
            }
            Component comp = renderer.getTableCellRendererComponent(tabla, tabla.getColumnModel().getColumn(columna).getHeaderValue(), false, false, 0, 0);
            int ancho = comp.getPreferredSize().width; // ancho de la cabecera de cada columna

            for (int fila = 0; fila < nroFilas; fila++) {
                renderer = tabla.getCellRenderer(fila, columna);
                comp = tabla.prepareRenderer(renderer, fila, columna);
                ancho = Math.max(comp.getPreferredSize().width, ancho);
            }
            TableColumnModel modeloColumna = tabla.getColumnModel();
            TableColumn columnaTabla = modeloColumna.getColumn(columna);
            columnaTabla.setPreferredWidth(ancho + 20);
        }
    }

//    public static void centrarCabecera(JTable table) {
//        DefaultTableCellRenderer renderer;
//        renderer = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
//        renderer.setHorizontalAlignment(JLabel.CENTER);
//    }
    public static void fondoBarraHerramientas(JToolBar barraHerramientas) {
        barraHerramientas.setUI(new BasicToolBarUI() {

            public void paint(Graphics g, JComponent c) {
//                g.setColor(Color.black);
//                g.drawRect(0, 0, c.getWidth(), c.getHeight());
                g.setColor(new Color(241, 246, 250));
                g.fillRect(0, 0, c.getWidth(), c.getHeight());


            }
        });
    }

    public static String formatearNumero(Object value) {
        double valor = 0d;
        try {
            if (value == null) {
                value = 0d;
            }
            valor = Double.parseDouble(value.toString());
            valor = Math.round(valor * 100) / 100.0d;
        } catch (NumberFormatException e) {
            valor = 0d;
        }
        /*
         * Verifica si es que existen comas y las reemplaza por puntos
         */
        return String.format("%.2f", valor).replaceAll(",", ".");
    }

//    public static void abrirDialogoImpresion(String ruta) {
//        SwingController controller = new SwingController();
//        SwingViewBuilder factory = new SwingViewBuilder(controller);
//        JPanel viewerComponentPanel = factory.buildViewerPanel();
//        ComponentKeyBinding.install(controller, viewerComponentPanel);
//        controller.getDocumentViewController().setAnnotationCallback(
//                new org.icepdf.ri.common.MyAnnotationCallback(
//                controller.getDocumentViewController()));
//        JDialog window = new JDialog(Principal.getInstance(), true);
//        window.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//        window.setTitle(".:: Impresión de Reportes ::.");
//        window.getContentPane().add(viewerComponentPanel);
//        window.pack();
//        window.setLocationRelativeTo(null);
//        if (ruta != null) {
//            controller.openDocument(ruta);
//        }
//        window.setVisible(true);
//    }
    public static void maximizarTodasLasVentanas(JInternalFrame ventanaCerrada) {
        try {
            ventanaCerrada.setVisible(false);
            JInternalFrame[] ventanas = Principal.getInstance().getEscritorio().getAllFrames();
            for (int i = ventanas.length - 1; i >= 0; i--) {
                JInternalFrame jInternalFrame = ventanas[i];
                jInternalFrame.setSelected(true);
                jInternalFrame.setMaximum(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String obtenerFechaDDMMYYYHHMMSS() {
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-[HHmmss]");
        Date date = new Date();
        return dateFormat.format(date);
    }

    public static String obtenerFechaDDMMYYY() {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();
        return dateFormat.format(date);
    }

    public static String convertirFechaDDMMYYY(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        return dateFormat.format(date);
    }

    public static String obtenerFechaHHMMSS() {
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
    
    public static String obtenerFechaHHMMSSAA() {
        DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss aa");
        Date date = new Date();
        return dateFormat.format(date);
    }
}